#!/usr/local/ActiveTcl/bin/wish8.5

set SCRIPT_DIR [file dirname $argv0];
if {$SCRIPT_DIR=="."} {set SCRIPT_DIR [pwd]}
source "$SCRIPT_DIR/lib/common_access.tcl"
source "$SCRIPT_DIR/lib/common_variable.tcl"
source "$SCRIPT_DIR/lib/proc_lib.tcl"
source "$SCRIPT_DIR/lib/tools_lib.tcl"
source "$SCRIPT_DIR/lib/runtest_lib.tcl"
source "$SCRIPT_DIR/lib/database_lib.tcl"
source "$SCRIPT_DIR/lib/tree1.tcl"
#source "$SCRIPT_DIR/lib/textprops.tcl"
source "$SCRIPT_DIR/lib/math_lib.tcl"
source "$SCRIPT_DIR/lib/sky_comm.tcl"

#log_user $log_to_monitor
package require Expect
package require Tk
package require msgcat
package require BWidget
package require math
package require http
#package require mysqltcl 3.0
package require json
package require md5
set DATA_DIR "$SCRIPT_DIR/data"
set LOG_DIR "$SCRIPT_DIR/log"
set SLEEP_RUN 0
set parent_env_for_pkg ""
set can_change "disabled" 
set run_in_bg 0
set dev_no 0
set test_no 0
set array1(0,0) ""
set array_test(0,0) ""
set change_dut1 0
set cp_env "0"
set map1(1,1) ""
set row1(4) ""
set row1(6) ""
set row1(7) ""
set row1(8) "FortiOS"
set cur_env "/"
set exp_log 0
set running_pid ""
set interrupt 0
set db_keepaliving 0

#if {![file isdirectory $DATA_DIR]} { file mkdir $DATA_DIR }
#if {![file isdirectory $LOG_DIR]} { file mkdir $LOG_DIR }

	
. config -bd 3 -relief flat
frame .f -bg white
pack .f -fill both -expand 1
image create photo idir -data {
    R0lGODdhEAAQAPIAAAAAAHh4eLi4uPj4APj4+P///wAAAAAAACwAAAAAEAAQAAADPVi63P4w
    LkKCtTTnUsXwQqBtAfh910UU4ugGAEucpgnLNY3Gop7folwNOBOeiEYQ0acDpp6pGAFArVqt
    hQQAO///
}
image create photo ifile -data {
    R0lGODdhEAAQAPIAAAAAAHh4eLi4uPj4+P///wAAAAAAAAAAACwAAAAAEAAQAAADPkixzPOD
    yADrWE8qC8WN0+BZAmBq1GMOqwigXFXCrGk/cxjjr27fLtout6n9eMIYMTXsFZsogXRKJf6u
    P0kCADv/
}
image create photo ipack -data {
    R0lGODdhEAAQAPIAAAAAAHh4eLi4uPj4+P///wAAAAAAAAAAACwAAAAAEAAQAAADPkixzPOD
    AAAAAAAqC8WN0+BZAmBq1GMOqwigXFXCrGk/AAAAAA7fLtout6n9eMIYMTXsFZsogXRKJf6u
    AAAAAAA/
}
image create photo idir_disable -file $SCRIPT_DIR/lib/folder_disable.GIF
image create photo ifile_disable -file $SCRIPT_DIR/lib/folder_disable.GIF
image create photo ipack_disable -file $SCRIPT_DIR/lib/folder_disable.GIF
frame .f.mb -bd 2 -relief raised
pack .f.mb -side top -fill x
menubutton .f.mb.file -text File -menu .f.mb.file.menu
catch {
  menu .f.mb.file.menu
  .f.mb.file.menu add command -label "Connect or Refresh database" -command {set db_keepaliving 0; refresh_display}
  .f.mb.file.menu add command -label "Import data from file" -command {import_file}
  .f.mb.file.menu add command -label "Reset log file" -command {reset_logfile}
  .f.mb.file.menu add command -label "User profile setting" -command {user_profile_setting}
###  .f.mb.file.menu add command -label "Upgrade test table" -command {upgrade_table}
  .f.mb.file.menu add command -label Quit -command close_db_and_exit
}
menubutton .f.mb.edit -text Edit -menu .f.mb.edit.menu
catch {
	menu .f.mb.edit.menu
  	.f.mb.edit.menu add command -label "New device" -command {edit_dev}
  	.f.mb.edit.menu add command -label "Manage device" -command {man_dev}
  	.f.mb.edit.menu add command -label "Manage test" -command {man_test}
  	.f.mb.edit.menu add command -label "Manage test group" -command {man_test_group}
	.f.mb.edit.menu add command -label "Options" -command {set_option}
}
menubutton .f.mb.tools -text Tools -menu .f.mb.tools.menu
catch {
	menu .f.mb.tools.menu
	.f.mb.tools.menu add command -label "Script_run" -command {script_run}
}
menubutton .f.mb.view -text View -menu .f.mb.view.menu
catch {
        menu .f.mb.view.menu
        .f.mb.view.menu add command -label "View current substition" -command {change_dut}
        .f.mb.view.menu add command -label "View test result" -command {view_result}
        .f.mb.view.menu add command -label "Create test result report" -command {report_result}
}

menubutton .f.mb.setup -text Database -menu .f.mb.setup.menu
catch {
        menu .f.mb.setup.menu
        .f.mb.setup.menu add command -label "Backup Database(local)" -command {database_backup}
        .f.mb.setup.menu add command -label "Restore Database(local)" -command {database_restore}
        .f.mb.setup.menu add separator
        .f.mb.setup.menu add command -label "Database Commit to SVN"  -command {database_commit}
        .f.mb.setup.menu add command -label "Database Update from SVN" -state disabled -command {database_update_date}
        .f.mb.setup.menu add separator
        .f.mb.setup.menu add command -label "Schedule Backup" -command {database_schedule_backup}
        .f.mb.setup.menu add command -label "Database Connection" -command {database_setup}
        .f.mb.setup.menu add separator
        .f.mb.setup.menu add command -label "Backup Database structure only" -command {database_backup_structure}
        .f.mb.setup.menu add command -label "Upgrade Database Structure" -command {database_upgrade_structure}
        .f.mb.setup.menu add command -label "Backup Database data only" -command {database_backup_data}
}

menubutton .f.mb.help -text Help -menu .f.mb.help.menu
catch {
	menu .f.mb.help.menu
	.f.mb.help.menu add command -label "About" -command {about_box}
}

pack .f.mb.file .f.mb.edit .f.mb.view .f.mb.tools .f.mb.setup .f.mb.help -side left -padx 10
Tree:create .f.w -width 150 -height 400 -yscrollcommand {.f.sb set}
Tree:newitem .f.w / -image idir
scrollbar .f.sb -orient vertical -command {.f.w yview}
pack .f.w -side left -fill both -expand 1 -padx 5 -pady 5
pack .f.sb -side left -fill y

frame .f.out_window  -bg white
pack .f.out_window -side left -fill both -expand 1
label .f.out_window.cur_title -text "        Current operation environment           " -padx 0 -width 30 -relief sunken
label .f.out_window.l -anchor nw -relief raised -padx 0 -pady 0 -text {} 
pack .f.out_window.cur_title -side top -fill both
pack .f.out_window.l -side top  -fill both
#frame .f.out_window.dev_list -bg white
#label .f.out_window.dev_list.title -text "Handle device list:" -padx 0 
frame .f.out_window.oper
pack .f.out_window.oper -side top -fill both -expand 0

set sw_dev_list [ScrolledWindow .f.out_window.oper.dev_sw -relief sunken -borderwidth 2]
set sff_dev_list [ScrollableFrame .f.out_window.oper.dev_sw.f -height 190 -width 300 -constrainedwidth 1 -bg white]
$sw_dev_list setwidget $sff_dev_list
set sf_dev_list [$sff_dev_list getframe]
pack $sw_dev_list -side left -fill both -expand 1 

set sw_test_list [ScrolledWindow .f.out_window.oper.test_sw -relief sunken -borderwidth 2]
set sff_test_list [ScrollableFrame .f.out_window.oper.test_sw.f -height 190 -width 300 -constrainedwidth 1 -bg grey]
$sw_test_list setwidget $sff_test_list
set sf_test_list [$sff_test_list getframe]
pack $sw_test_list -side right -fill both -expand 1

#pack .f.out_window.dev_list -side top -fill both  
#pack .f.out_window.dev_list.title -side top -fill both
set cmd_win [frame .f.out_window.cmd]
pack $cmd_win -fill x -expand 0
#       catch {destroy $cmd_win.run}
#       catch {destroy $cmd_win.check}
button $cmd_win.conf -text "Config Env" -command { start_running; run_env $cur_env; stop_running  } -anchor e
button $cmd_win.check_conf -text "Uncheck All Device" -command " check_uncheck_conf $cmd_win" -anchor e
button $cmd_win.test -text "Test" -command "start_running; run_test $cur_env; stop_running " -anchor e
button $cmd_win.check_test -text "Uncheck All Test" -command " check_uncheck_test $cmd_win" -anchor e
#change_test proc is for changing table from old env_test to test and new env_test
#button $cmd_win.set_dut -text "Change DUT" -command "change_test" -anchor e
button $cmd_win.set_dut -text "Change DUT" -command "change_dut" -anchor e
button $cmd_win.stop -text "Stop Running" -command " interrupt_run" -anchor e -state disabled 

pack $cmd_win.conf -side left -expand 0 -anchor w
pack $cmd_win.check_conf -side left -expand 0 -anchor w
pack $cmd_win.set_dut -side left -expand 0 -anchor w
pack $cmd_win.check_test -side right -expand 0 -anchor w
pack $cmd_win.test -side right -expand 0 -anchor w
pack $cmd_win.stop -side left -expand 1 -anchor w


label .f.out_window.title -text "Information Window" -padx 0 -width 30 -relief raised
set info [text .f.out_window.info -borderwidth 5 -relief sunken -setgrid true -yscrollcommand {.f.out_window.scrollY set}]
scrollbar .f.out_window.scrollY -command {.f.out_window.info yview}
pack .f.out_window.title -side top -fill x 
pack .f.out_window.scrollY -side right -fill y
pack .f.out_window.info -side left -fill both -expand 1

#Initialization checking. Check file cfg/user_info.txt existence. and, if user info is enough. return 1 means enough, return 0 means "not enough", then we have to do initial_user_setting later
set user_str [initial_user_checking]
set old_user [lindex $user_str 0]
log_info $info "old_user is $old_user" 2
if {$old_user == "0"} {
    log_info $info "setup random username" 2
    set username "user"
    append username [expr {int(rand()*20000)}]

    set password "123456"
    user_profile_setting
} else {
    set user_id [lindex $user_str 1]
    set user_pwd [lindex $user_str 2]
    set group_id [lindex $user_str 3]
    set group_pwd [lindex $user_str 4]
}
set user_raw_pwd "Original_User_Pwd_a2B3c4D5"
set group_raw_pwd "Original_Group_Pwd_a2B3c4D5"

set operator $user_id

.f.out_window.cur_title configure -text "        Current operation environment            user_id:$user_id    group_id:$group_id"


#set db_handle [::mysql::connect -host $DB_SERVER -user $DB_USER -password $DB_PASS -db $DB_NAME -foundrows 1]
#set db_prv_handle [::mysql::connect -host $DB_PRV_SERVER -user $DB_PRV_USER -password $DB_PRV_PASS -db $DB_PRV_NAME -foundrows 1]


#rename puts command to push output of puts to info window
#rename puts _puts
#proc puts {args} {
#	global info
#	log_info $info "$args" 7
#}

rename exp_close _orig_exp_close
proc exp_close {args} {
    uplevel _orig_exp_close $args
    exp_wait
}
proc reset_logfile {} {
	global SCRIPT_DIR
	log_file
	log_file -a -noappend $SCRIPT_DIR/log/access.log
	log_user 1
	# below two lines change stdout to file
	close stdout
	open $SCRIPT_DIR/log/stdout.log w
}
proc kill_running_pid {} {
	global running_pid info
        foreach pid [split $running_pid ";"] {
                log_info $info "kill pid: $pid" 2
                if {[string trim $pid]!=""} { 
			catch {exec kill -9 $pid}
		#	exec kill -9 $pid
		}
        }
	set running_pid ""
}
proc interrupt_run {} {
	global running_pid interrupt cmd_win info run_in_bg
	if {[$cmd_win.stop cget -text]=="Stop" } {
		set interrupt 1
		log_info $info "system interrupted manually. program is exiting all connection" 2
		kill_running_pid
		stop_running
		log_info $info "system interrupted manually. finished to exit all connection" 2
	} elseif  {[$cmd_win.stop cget -text]=="Continue"} {
		set run_in_bg 1
		$cmd_win.stop configure -state normal -text "Stop"
		log_info $info "Stop pausing, continue to run" 2
	} else {
		log_info $info "cmd_win.stop text is neither Stop or Continue!should never happen" 2
	}
}
proc start_running {} {
	global run_in_bg cmd_win running_pid interrupt run_case_no run_case_no_min run_case_no_max parent_env_for_pkg info
	set parent_env_for_pkg ""
	set running_pid ""
	if {$run_in_bg==0} {
        	set run_in_bg 1
        	set interrupt 0
		set run_case_no [::math::random $run_case_no_min $run_case_no_max]
        	$cmd_win.stop configure -state normal -text "Stop"
        	$cmd_win.conf configure -state disabled
        	$cmd_win.check_conf configure -state disabled
        	$cmd_win.set_dut configure -state disabled
        	$cmd_win.check_test configure -state disabled
        	$cmd_win.test configure -state disabled
        } elseif {$run_in_bg==2} {
	        $cmd_win.stop configure -state disabled
        	$cmd_win.test configure -state disabled
	} else {
		log_info $info "Strange!!!it's already in run state!" 2
	}
}
proc pause_running {} {
	global run_in_bg cmd_win
	set run_in_bg 2
        $cmd_win.stop configure -state normal -text "Continue"
	$cmd_win.test configure -state normal
        $cmd_win.conf configure -state normal
        $cmd_win.check_conf configure -state normal
        $cmd_win.set_dut configure -state normal
        $cmd_win.check_test configure -state normal

	tkwait variable run_in_bg
#	while {$run_in_bg==0} {
#		###Wait until user click stop butten which will change run_in_bg to 1
#		sleep 1
#	}
}
proc stop_running {} {
	global run_in_bg cmd_win info
	if {$run_in_bg==1} {
        	set run_in_bg 0
        	$cmd_win.stop configure -state disabled -text "Stop"
        	$cmd_win.conf configure -state normal
        	$cmd_win.check_conf configure -state normal
        	$cmd_win.set_dut configure -state normal
        	$cmd_win.check_test configure -state normal
        	$cmd_win.test configure -state normal
	} elseif {$run_in_bg==2} {
        	#$cmd_win.stop configure -state disabled -text "Stop"
		$cmd_win.test configure -state normal
		$cmd_win.stop configure -state normal
	} else {
        	#$cmd_win.stop configure -state disabled -text "Stop"
		log_info $info "Strange!!!it's already in stop state!" 2
	}
}

	
proc alert_running {} {
	global info
	log_info $info "System is running, you have to stop running before doing anything else" 2
}

#we reset two log file when problem reload by default
reset_logfile

#connect to database
#display_database $DB_SERVER $DB_USER $DB_PASS $DB_NAME $TREE_TB 
#Tree:newitem .f.w /sample -image idir
#create a popupmunu for right click
set popup1 [menu .popupmenu]
$popup1 add command -label "new sub-env" -command {
	add_env;
	log_info $info "add_env finished, now refresh database" 4;
	refresh_display;
	#display_database $DB_SERVER $DB_USER $DB_PASS $DB_NAME $TREE_TB;
	log_info $info "refresh database finished" 4;
}
$popup1 add command -label "Attach package" -command {
	add_pack $cur_env;
	#doesnot have commit in add_pack, so below commands are useless because they will be executed immediately
	#log_info $info "attach package finished, now refresh database" 4;
	#display_database $DB_SERVER $DB_USER $DB_PASS $DB_NAME $TREE_TB;
	#log_info $info "refresh database finished" 4;
	}
$popup1 add command -label "remove current env" -state $can_change -command {rem_env $cur_env }
$popup1 add command -label "rename current env" -state $can_change -command {chg_name_env $cur_env }
$popup1 add command -label "copy current env" -command {set cp_env $cur_env }
$popup1 add command -label "paste env" -command {paste_env $cur_env $cp_env}
$popup1 add command -label "export current env"  -command {export_env $cur_env }
$popup1 add command -label "create testcases document(table mode)"  -command {document_env $cur_env table}
$popup1 add command -label "create testcases document(single case mode)"  -command {document_env $cur_env singlecase }
$popup1 add separator
#$popup1 add command -label "add device for this test" -command {add_env_dev .f.out_window.dev_list}
$popup1 add command -label "add device for this env" -command "add_env_dev"
$popup1 add command -label "add DUT substitute " -command "add_env_subst subst_dut"
$popup1 add command -label "add Support devices substitute " -command "add_env_subst subst_others"
$popup1 add command -label "chg device under this env" -command {chg_env_dev $cur_env}
$popup1 add command -label "add test for this env" -command {add_env_test 1 ""}
$popup1 add command -label "Create new test" -command "edit_env_test_new 0"
$popup1 add separator
$popup1 add command -label "Config&Run all test in current env" -command {
	if {$run_in_bg==0} {
		start_running;
		conf_run_env $cur_env;
		stop_running;
	} else {
		alert_running;
	} }

$popup1 add command -label "Config&Run all test in current env(include sub_env)" -command {
	if {$run_in_bg==0} {
		start_running;
		#Below puts command if for recording info in stdout file
		puts "start running!!!!"
		conf_run_env_all $cur_env; 
		stop_running;
	} else {
		alert_running
	}}
$popup1 add separator
$popup1 add command -label "Edit description of this env" -command {edit_env_des $cur_env}
bind .f.w <3> {
#	$info insert end "w: %W; x: %x ; y: %y;[Tree:labelat %W %x %y] !\n"
#	$info see end
#	set cur_env %w
#	set row1(2) [string range [Tree:labelat %W %x %y] 1 end]
#	set cur_env $row1(2)
	set cur_env [string range [Tree:labelat %W %x %y] 1 end]
	if {$cur_env==""} {set cur_env "0"}
	set can_change [can_i_change $operator $cur_env]
#	$popup1 entryconfigure 1 -state $can_change
#	$popup1 entryconfigure 2 -state $can_change
	$popup1 entryconfigure 3 -state $can_change
	$popup1 entryconfigure 4 -state $can_change
#	$popup1 entryconfigure 6 -state $can_change
#	$popup1 entryconfigure 11 -state $can_change
#	$popup1 entryconfigure 12 -state $can_change
#	$popup1 entryconfigure 13 -state $can_change
#	$popup1 entryconfigure 14 -state $can_change
#	$popup1 entryconfigure 15 -state $can_change
	tk_popup $popup1 %X %Y
}

.f.w bind x <1> {
	if {$run_in_bg==0} {
                set lbl [Tree:labelat %W %x %y]
                Tree:setselection %W $lbl
                .f.out_window.l config -text "current env: $lbl"
                set cur_env [string range $lbl 1 end]
                list_dev_for_env $sf_dev_list $cur_env
                list_test_for_env $sf_test_list $cur_env
                $cmd_win.check_test configure -text "Uncheck All Test"
                $cmd_win.check_conf configure -text "Uncheck All Device"
	} else {
		alert_running
	}
}

update
#.f.w bind x <Double-1> {
#  Tree:open %W [Tree:labelat %W %x %y]
#}
